package org.vison.wonfu.framework.soa.discovery;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.vison.wonfu.framework.soa.annotation.LoadBalance;

import javax.annotation.Resource;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

public abstract class AbstractServiceRegistryDiscovery implements ServiceRegistryDiscovery {

    private List<LoadBalanceAlgorithm> loadBalanceAlgorithms = new ArrayList<>();
    private Map<LoadBalance,LoadBalanceAlgorithm> loadBalanceAlgorithmMap = new HashMap<>();

    public AbstractServiceRegistryDiscovery() {
        ServiceLoader<LoadBalanceAlgorithm> serviceLoader = ServiceLoader.load(LoadBalanceAlgorithm.class);
        for(LoadBalanceAlgorithm algorithm : serviceLoader) {
            loadBalanceAlgorithms.add(algorithm);
            loadBalanceAlgorithmMap.put(algorithm.getType(), algorithm);
        }

    }

    public ServiceInstance loadbalanceSelect(List<ServiceInstance> instances,LoadBalance loadBalance) {
        LoadBalanceAlgorithm algorithm = loadBalanceAlgorithmMap.get(loadBalance);
        algorithm.setServiceInstances(instances);
        return algorithm.select();
    }

}
